package com.hengtongxing.hejiayun_employee.homepage;


import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import com.google.gson.Gson;
import com.hengtongxing.hejiayun_employee.R;
import com.hengtongxing.hejiayun_employee.base.Adapter_ViewPager_Fragment;
import com.hengtongxing.hejiayun_employee.base.BaseFragment;
import com.hengtongxing.hejiayun_employee.base.DataCallBack;
import com.hengtongxing.hejiayun_employee.bean.UserInfoBean;
import com.hengtongxing.hejiayun_employee.event.LoginEvent;
import com.hengtongxing.hejiayun_employee.mine.model.MineModelImpl;
import com.hengtongxing.hejiayun_employee.utils.Dp2Px;
import com.hengtongxing.hejiayun_employee.utils.SPManager;
import com.hengtongxing.hejiayun_employee.widget.ChildColorTitleView;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.badge.BadgeAnchor;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.badge.BadgePagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.badge.BadgeRule;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 首页
 */
public class HomePageFragment extends BaseFragment {

    @BindView(R.id.iv_header)
    ImageView ivHeader;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.magic_indicator)
    MagicIndicator magicIndicator;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.tv_type_name)
    TextView tvTypeName;
    private List<String> mDataList;
    private Adapter_ViewPager_Fragment adapter_viewPager;
    private CommonNavigator commonNavigator;
    private UserInfoBean userInfoBean;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home_page, container, false);
        ButterKnife.bind(this, view);
        registerEventBus();
        initView();
        requestUserInfo();
        return view;
    }

    @Subscribe
    public void loginEvent(LoginEvent event) {
        initView();
        requestUserInfo();
    }

    public void initView() {
        userInfoBean = new Gson().fromJson(SPManager.getInstance().getUserInfoJson(), UserInfoBean.class);
        mDataList = new ArrayList<>();
        if (userInfoBean.getData().getType() == 3) {
            mDataList.add("新任务");
            mDataList.add("待解决");
            mDataList.add("已维修");
            mDataList.add("已完成");
        }
        if (userInfoBean.getData().getType() == 2) {
            mDataList.add("新任务");
            mDataList.add("待解决");
            mDataList.add("已完成");
        }
        if (userInfoBean.getData().getType() == 4) {
            mDataList.add("待配货");
            mDataList.add("已配货");
        }
        if (userInfoBean.getData().getType() == 5) {
            mDataList.add("待配送");
            mDataList.add("已配送");
        }
        if (userInfoBean.getData().getType() == 1) {
            mDataList.add("新任务");
            mDataList.add("待解决");
            mDataList.add("已保洁");
            mDataList.add("已完成");
        }
        //ViewPager的适配器
        List<BaseFragment> fragmentList = new ArrayList<>();
        for (String title : mDataList) {
            //
            if (userInfoBean.getData().getType() == 3) {
                RepairFragment fragment = new RepairFragment();
                Bundle arguments = new Bundle();
                arguments.putString(RepairFragment.ORDER_TITLE_NAME, title);
                fragment.setArguments(arguments);
                fragmentList.add(fragment);
            }

            if (userInfoBean.getData().getType() == 2) {
                AdvisoryFragment fragment = new AdvisoryFragment();
                Bundle arguments = new Bundle();
                arguments.putString(AdvisoryFragment.ORDER_TITLE_NAME, title);
                fragment.setArguments(arguments);
                fragmentList.add(fragment);
            }
            if (userInfoBean.getData().getType() == 4) {
                ShopOrderFragment fragment = new ShopOrderFragment();
                Bundle arguments = new Bundle();
                arguments.putString(ShopOrderFragment.ORDER_TITLE_NAME, title);
                fragment.setArguments(arguments);
                fragmentList.add(fragment);
            }
            if (userInfoBean.getData().getType() == 5) {
                ShopDeliveryFragment fragment = new ShopDeliveryFragment();
                Bundle arguments = new Bundle();
                arguments.putString(ShopDeliveryFragment.ORDER_TITLE_NAME, title);
                fragment.setArguments(arguments);
                fragmentList.add(fragment);
            }
            if (userInfoBean.getData().getType() == 1) {

                HousekeepFragment fragment = new HousekeepFragment();
                Bundle arguments = new Bundle();
                arguments.putString(HousekeepFragment.ORDER_TITLE_NAME, title);
                fragment.setArguments(arguments);
                fragmentList.add(fragment);
            }

        }
        adapter_viewPager = new Adapter_ViewPager_Fragment(getChildFragmentManager(), fragmentList, mDataList);
        viewPager.setAdapter(adapter_viewPager);
        //指示器适配
        initMagicIndicator();
    }

    private void initMagicIndicator() {
        commonNavigator = new CommonNavigator(mActivity);
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mDataList == null ? 0 : mDataList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                ChildColorTitleView simplePagerTitleView = new ChildColorTitleView(context);
                simplePagerTitleView.setText(mDataList.get(index));
                simplePagerTitleView.setTextSize(16);
                simplePagerTitleView.setNormalColor(Color.parseColor("#D1FED1"));
                simplePagerTitleView.setSelectedColor(Color.parseColor("#FFFFFF"));
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        viewPager.setCurrentItem(index);
                    }
                });
                //创建一个角标注入到当前Tab
                BadgePagerTitleView badgePagerTitleView = new BadgePagerTitleView(context);
                badgePagerTitleView.setInnerPagerTitleView(simplePagerTitleView);

                int randNum = (int) (Math.random() * 10);
                String textValue = "";
                if (randNum > 99) {
                    textValue = "99+";
                } else {
                    textValue = String.valueOf(randNum);
                }

                //创建一个TextView来显示角标
                TextView badgeTextView = new TextView(context);
                badgeTextView.setText(textValue);
                badgeTextView.setTextColor(Color.WHITE);
                badgeTextView.setTextSize(8);
                badgeTextView.setGravity(Gravity.CENTER);
                badgeTextView.setLayoutParams(new FrameLayout.LayoutParams((int) Dp2Px.dp2Px(14), (int) Dp2Px.dp2Px(14)));
                badgeTextView.setBackgroundResource(R.drawable.circle_red_bg);
                badgeTextView.setVisibility(View.GONE);
                badgePagerTitleView.setBadgeView(badgeTextView);
                //定位角标位于Tab的X，Y轴的位置
                badgePagerTitleView.setXBadgeRule(new BadgeRule(BadgeAnchor.CONTENT_RIGHT, -5));
                badgePagerTitleView.setYBadgeRule(new BadgeRule(BadgeAnchor.CONTENT_TOP, -15));
                badgePagerTitleView.setAutoCancelBadge(false);
                return badgePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                indicator.setLineHeight(UIUtil.dip2px(context, 4));
                indicator.setLineWidth(UIUtil.dip2px(context, 48));
                indicator.setColors(Color.parseColor("#FFFFFF"));
                return indicator;
            }

            @Override
            public float getTitleWeight(Context context, int index) {
                return 1.0f;
            }

        });
        magicIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(magicIndicator, viewPager);
        viewPager.setOffscreenPageLimit(3);
    }

    //写个类继承ColorTransitionPagerTitleView，在onEnter设置 setTypeface(Typeface.DEFAULT_BOLD); onLeave中
    //setTypeface(Typeface.DEFAULT);
    @Override
    public void onResume() {
        super.onResume();
        requestUserInfo();
    }

    private boolean isViewCreated; // 界面是否已创建完成
    private boolean isVisibleToUser; // 是否对用户可见

    /**
     * Fragment 创建期间setUserVisibleHint()方法是在onActivityCreated()之前被调用
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        tryLoadData();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewCreated = true;
        tryLoadData();
    }

    public void tryLoadData() {
        if (isViewCreated && isVisibleToUser) {
            requestUserInfo();
        }
    }

    public void requestUserInfo() {
        new MineModelImpl().requestMine(new DataCallBack<UserInfoBean>() {
            @Override
            public void onSuccessful(UserInfoBean bean) {
                tvName.setText(bean.getData().getName());
                tvTypeName.setText(userInfoBean.getData().getType_text());
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }
}